package ocg.http.httpcore;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.JsonPath;
import ocg.common.re.reports.TestReport;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chenbo on 2018/4/25.
 */
public class HttpResponse {

    private Logger logger = LogManager.getLogger ( this.getClass () );

    public int Status = 0;
    public HttpEntity entity = null;
    private TestReport apiReport;
    public Header[] responseHeaders;
    public String data[][];
    public String body = null;

    public HttpResponse( CloseableHttpResponse httpResponse ,TestReport apiReport ){
        this.apiReport = apiReport;
        this.patser(httpResponse);
    }

    public HttpResponse( CloseableHttpResponse httpResponse ){
        this.patser(httpResponse);
    }

    private void patser( CloseableHttpResponse httpResponse ){
        if ( httpResponse != null) {
            this.Status = httpResponse.getStatusLine ().getStatusCode ();
            int size = httpResponse.getAllHeaders ().length;

            data= new String[size][2];
            responseHeaders = new Header[size];

            for (int i = 0; i < size; i++) {
                responseHeaders[i] = httpResponse.getAllHeaders ()[i];
                logger.debug ( "Response-header: " + responseHeaders[i] );
                data[i][0] = responseHeaders[i].getName();
                data[i][1] = responseHeaders[i].getValue();
            }

            apiReport.log_info("response-header: ", data );
            try {
                this.entity = new BufferedHttpEntity ( httpResponse.getEntity () );
                this.body = EntityUtils.toString ( entity );
                logger.debug ( "Response-body: " +  body );
                apiReport.log_info_Code("response-body: " , body );
            } catch (IOException e) {
                e.printStackTrace ();
            }

        }
    }

    public JSONObject jsonBody(){

        if ( body != null) {
            return JSON.parseObject ( body );
        }

        return null;
    }

    public <T>T jsonPath( String path ){

        return JsonPath.parse ( body ).read ( path );

    }

    public Matcher matcher( String regex ){

        Pattern pattern = Pattern.compile ( regex );

        Matcher matcher = pattern.matcher( body );

        return matcher;
    }
}
